import io
import os

import pandas as pd


def sql_execute():
    # 项目路径
    BASE_DIR = os.path.dirname(os.path.abspath('base_dir'))
    # 静态文件夹的路径,项目路径拼接向下的文件夹
    STATIC_DIR = os.path.join(BASE_DIR, 'static')
    sqls_path = os.path.join(STATIC_DIR, 'sqls')
    excels_path = os.path.join(STATIC_DIR, 'excels')

    # 创建3个文件
    rfq44_file = io.open(sqls_path + "\\rfq44_file.sql", 'a', encoding='utf-8')
    rfq_not44_file = io.open(sqls_path + "\\rfq_not44_file.sql", 'a', encoding='utf-8')
    dfq_file = io.open(sqls_path + "\\dfq_file.sql", 'a', encoding='utf-8')
    select_file = io.open(sqls_path + "\\select_file.sql", 'a', encoding='utf-8')


    # 读取文件
    file_loc = sqls_path + "\\insert_sql.txt"
    target_file = sqls_path + "\\target.txt"
    with open(file_loc, "r", encoding='utf-8') as txt:
        for txt_line in txt.readlines():
            rfq_pos1 = txt_line.find("ION(") + 4
            rfq_pos2 = txt_line.find(")")
            # 表名位置
            pos1 = txt_line.find(".")
            pos2 = txt_line.find(" PARTITION(")
            # print(txt_line[pos1 + 1:pos2])
            if txt_line.find('PARTITION') != -1:
                if txt_line[rfq_pos1:rfq_pos2].find(',') == -1:
                    # 单分区
                    with open(target_file, "r", encoding='utf-8') as target:
                        for table_name in target.readlines():
                            if txt_line[pos1 + 1:pos2] == table_name:
                                rfq44_file.write(txt_line)
                            else:
                                rfq_not44_file.write(txt_line)
                else:
                    # 多分区
                    dfq_file.write(txt_line)
            select_pos1=txt_line.find('SELECT')
            select_pos2=txt_line.find(" WHERE")
            select_file.write(txt_line[select_pos1:select_pos2]+"\n")
            # print(txt_line[select_pos1:select_pos2])

    rfq44_file.close()
    rfq_not44_file.close()
    dfq_file.close()


if __name__ == '__main__':
    sql_execute()
